'use client'

import React, { useState } from 'react'
import { toast } from 'react-hot-toast'
import Button from '@/components/ui/Button'

interface GroupMember {
  id: string
  name: string | null
  email: string
  submissionId?: string
  currentScore?: number | null
}

interface GroupGradeInputProps {
  experimentId: string
  groupMembers: GroupMember[]
  groupName: string
  onScoresUpdated: (updates: { submissionId: string; score: number }[]) => void
}

export default function GroupGradeInput({
  experimentId,
  groupMembers,
  groupName,
  onScoresUpdated
}: GroupGradeInputProps) {
  const [groupScore, setGroupScore] = useState<string>('')
  const [isUpdating, setIsUpdating] = useState(false)
  const [showInput, setShowInput] = useState(false)

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (groupScore === '') {
      toast.error('请输入小组分数')
      return
    }

    const scoreValue = parseFloat(groupScore)
    if (isNaN(scoreValue) || scoreValue < 0 || scoreValue > 100) {
      toast.error('分数必须在0-100之间')
      return
    }

    // 过滤出有提交记录的成员
    const membersWithSubmissions = groupMembers.filter(member => member.submissionId)
    
    if (membersWithSubmissions.length === 0) {
      toast.error('该小组没有成员提交实验')
      return
    }

    setIsUpdating(true)
    toast.loading(`正在为小组 ${groupName} 录入分数...`, { id: 'group-grade-update' })

    try {
      const updates = []
      
      // 为每个有提交记录的成员录入相同分数
      for (const member of membersWithSubmissions) {
        const response = await fetch(`/api/experiments/${experimentId}/submissions/${member.submissionId}/quick-grade`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ score: scoreValue }),
        })

        if (!response.ok) {
          const errorData = await response.json().catch(() => ({}))
          throw new Error(`为 ${member.name || member.email} 保存分数失败: ${errorData.message}`)
        }

        updates.push({ submissionId: member.submissionId!, score: scoreValue })
      }

      onScoresUpdated(updates)
      setShowInput(false)
      setGroupScore('')
      toast.success(`已为小组 ${groupName} 的 ${membersWithSubmissions.length} 名成员录入分数: ${scoreValue}分`, { id: 'group-grade-update' })
    } catch (error: any) {
      console.error('保存小组分数错误:', error)
      toast.error(error.message || '保存小组分数失败', { id: 'group-grade-update' })
    } finally {
      setIsUpdating(false)
    }
  }

  const handleCancel = () => {
    setGroupScore('')
    setShowInput(false)
  }

  const membersWithSubmissions = groupMembers.filter(member => member.submissionId)
  const hasSubmissions = membersWithSubmissions.length > 0

  if (!showInput) {
    return (
      <div className="flex items-center space-x-2">
        <span className="text-sm text-gray-600">
          小组成员: {groupMembers.length} 人
          {hasSubmissions && ` (${membersWithSubmissions.length} 人已提交)`}
        </span>
        <Button
          variant="ghost"
          size="sm"
          onClick={() => setShowInput(true)}
          disabled={!hasSubmissions}
          className="text-primary-600 hover:text-primary-800"
        >
          批量录入
        </Button>
      </div>
    )
  }

  return (
    <div className="space-y-3">
      <div className="text-sm text-gray-600">
        将为小组 "{groupName}" 的 {membersWithSubmissions.length} 名已提交成员录入相同分数
      </div>
      <form onSubmit={handleSubmit} className="flex items-center space-x-2">
        <input
          type="number"
          value={groupScore}
          onChange={(e) => setGroupScore(e.target.value)}
          placeholder="0-100"
          min="0"
          max="100"
          step="0.1"
          className="w-20 px-2 py-1 text-sm border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-primary-500"
          disabled={isUpdating}
          autoFocus
        />
        <Button
          type="submit"
          variant="primary"
          size="sm"
          disabled={isUpdating}
        >
          批量保存
        </Button>
        <Button
          type="button"
          variant="ghost"
          size="sm"
          onClick={handleCancel}
          disabled={isUpdating}
        >
          取消
        </Button>
      </form>
    </div>
  )
} 